/*
 * CommProtocol.h
 *
 * Created: 11/1/2011 6:53:05 PM
 *  Author: erikko
 */ 


#ifndef COMMPROTOCOL_H_
#define COMMPROTOCOL_H_

#include "avr_compiler.h"
#include <avr/io.h>
#include "usart_driver.h"
#include "pc_com.h"
//#include "varpot.h"

USART_data_t USART_data[4];
USART_t* USARTptrs[4];

#define MAX_PACKET_SIZE 64
#define ETX_SIZE 1
#define STX_SIZE 1
#define CKSUM_SIZE 4 // uint_16t before Manchester encoding.
#define MAX_MESSAGE_SIZE (MAX_PACKET_SIZE-ETX_SIZE-STX_SIZE-CKSUM_SIZE)/2
#define MAX_QUEUE 5
//#define DATA_QUEUE_SIZE MAX_MESSAGE_SIZE*MAX_QUEUE

#define STX 0b10011101
#define ETX 0b10111001

// This is the first place incoming data goes, and the last place outgoing data goes before the UART.
// There should be only one for each UART.
typedef enum Direction {
	NORTH,
	SOUTH,
	EAST,
	WEST
} Direction_e;

typedef struct Packet {
	uint8_t data[MAX_PACKET_SIZE]; // Where incoming data goes.  Includes 1byte STX, 1byte ETX, 2byte Checksum.
	uint8_t length; // The length of the complete message contained in data.
	uint8_t position; // For outgoing packets, the next byte to send.  For incoming packets, the next byte to place.
	uint8_t valid; // True if there is a complete and valid message in data (STX at data[0], ETX at data[length-1].
} Packet_t;

typedef struct MsgInfo {
	uint8_t data[MAX_MESSAGE_SIZE]; // Outgoing data.
	uint8_t length; // How much of data is actually data.
	uint8_t priority; // Higher is higher priority.  0 means the data is invalid.
	uint8_t power; // Sets the variable potentiometer.
} MsgInfo_t;

typedef struct DataQueue {
	MsgInfo_t slots[MAX_QUEUE];
} DataQueue_t;

Packet_t IncomingPacket[4];
Packet_t OutgoingPacket[4];
DataQueue_t OutQueue[4];
DataQueue_t InQueue[4];

void PrepareIncomingPacket(Direction_e dir);
void PrepareOutgoingPacket(Direction_e dir);
uint16_t checksum(uint16_t *buf, uint8_t count);
void fletcher16( uint8_t *checkA, uint8_t *checkB, uint8_t *data, uint8_t len );
void TestComm();
uint8_t encodeByte( uint8_t inByte );
uint8_t decodeByte( uint8_t inByte );
void encodeBytes(uint8_t *inBytes, uint8_t *outBytes, int count);
void decodeBytes(uint8_t *inBytes, uint8_t *outBytes, int count);
void ReceivedByte(uint8_t inbyte, Direction_e dir);
void TransmittedByte(Direction_e dir);

#endif /* COMMPROTOCOL_H_ */